<template>
  <BasicDrawer
    v-bind="$attrs" @register="registerDrawer" title="登录配置" width="700px"
    showFooter destroy-on-close @ok="handleSubmit(true)"
  >
    <BasicForm @register="registerForm">

      <template #loginScenes="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="20" :md="20" :lg="20" :xl="20">
            <JDictSelectTag
              placeholder="请选择" mode="multiple" :value-to-string="false"
              v-model:value="model[field]" :dictType="DictEnum.LoginScene" showSearch
            />
          </a-col>
          <a-col :sm="4" :md="4" :lg="4" :xl="4">
            <a-button type="primary" block style="width: 100%" @click="handleConfigDict(DictEnum.LoginScene)">管理</a-button>
          </a-col>
        </a-row>
      </template>

      <template #bindClient="{ model, field }">
        <MyCheckbox v-model:value="checkedClient" :options="clientOptions" />
      </template>
      <template #diyForm="{ model, field }">
        <a-button type="link" @click="handleOpenField">去配置</a-button>
      </template>
    </BasicForm>
    <DictItemList @register="registerDictItemList" />

  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, onMounted, nextTick } from "vue"
  import { JDictSelectTag } from "/@/components/Form"
  import { BasicDrawer, useDrawer, useDrawerInner } from "/@/components/Drawer"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import * as extIdpApi from "/@/api/iam/extIdp"
  import { formSchema, fieldColumns } from "./data"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { PageEnum } from "/@/enums/pageEnum"
  import { MyCheckbox } from "/@/components/Form/index"
  import { listClient } from "/@/views/system/oauthClient/api"
  import DictItemList from "/@/views/infra/dict/components/DictItemList.vue"
  import DictEnum from '/@/enums/dictEnum'
  import { saveOrUpdateDiyForm } from "/@/api/infra/diyForm"
  import { openWindow } from "/@/utils"
  import { useModal } from "/@/components/Modal"

  const clientOptions = ref<any[]>([])
  const { createMessage, createConfirm } = useMessage()
  const idpConnectTmpl = ref<any>({})
  const idpTmplId = ref<any>()
  const [registerDictItemList, { openDrawer: openDictList }] = useDrawer()

  const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 80,
    baseColProps: { lg: 24, md: 24 },
    wrapperCol: { lg: 24, md: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  })
  const emit = defineEmits(["success", "register"])

  const loading = ref(false)
  const checkedClient = ref<string>()
  const isUpdate = ref(true)
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await reset()
    idpConnectTmpl.value = unref(data.record)
    idpTmplId.value = data.idpTmplId

    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate
      console.log("data", idpConnectTmpl.value)

      if (unref(isUpdate)) {
        let oauthClientResp
        if (idpConnectTmpl.value.grantType) {
          oauthClientResp = await listClient({ extGrantType: idpConnectTmpl.value.grantType })
          clientOptions.value = oauthClientResp.list?.map((e) => ({
            label: e.name,
            value: e.id,
          }))
          checkedClient.value = oauthClientResp.checkedList?.join(",")
        }
        nextTick(async () => {
          await setFieldsValue({
            ...unref(idpConnectTmpl),
            hasClient: clientOptions.value.length > 0 ? "1" : "0",
            scenes: idpConnectTmpl.value.scenes?.split(","),
          })
        })
      }
    } catch(e) {
      console.error(e)
      createMessage.error("数据初始化失败")
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const handleConfigDict = (typeCode) => openDictList(true, { typeCode })
  const handleGoConfigParams = (configKey) => {
    console.log("configKey", configKey)

    if (!configKey || configKey === "" || configKey?.length === 0) {
      createMessage.warning("请先选择配置")
      return
    }
    const url = `${PageEnum.CONFIG_CENTER}?configKey=${configKey}`
    window.open(url, "_blank")
  }

  const reset = async () => {
    await resetFields()
    clientOptions.value = []
    idpConnectTmpl.value = {}
    checkedClient.value = ""
  }

  const handleOpenField = async () => {
    const url = `/onlineDev/formDesigner`
    let values = await validate()
    const diyFormId = values?.diyFormId
    if (!diyFormId || !values?.id) {
      createConfirm({
        iconType: "warning",
        title: "保存提示",
        content: "当前连接尚未保存，确定要保存并创建Diy表单吗？",
        onOk: async () => {
          const dataId = await saveOrUpdateDiyForm(
            {
              id: diyFormId,
              name: values.name,
              submitType: 1,
              canDelete: false
            },
            diyFormId
          )
          await setFieldsValue({ diyFormId: dataId })
          await handleSubmit(false)
          openWindow(`${url}?id=${dataId}`)
        },
        onCancel: () => console.log('已取消'),
      })
    } else {
      openWindow(`${url}?id=${diyFormId}`)
    }
  }
  async function handleSubmit(exit) {
    setDrawerProps({ confirmLoading: true })
    try {
      let values = await validate()
      delete values["bindClient"]
      const form = {
        ...values,
        idpTmplId: unref(idpTmplId),
        authClientIds: unref(checkedClient)?.split(","),
      }
      console.log("form", form)

      loading.value = true
      const dataId = await extIdpApi.saveIdpConnectTmpl(form, unref(isUpdate))
      await setFieldsValue({ id: dataId })
      idpConnectTmpl.value = { ...form, id: dataId }
      isUpdate.value = true

      exit && closeDrawer()
      exit && emit("success")
      createMessage.success("保存成功")

    } finally {
      setDrawerProps({ confirmLoading: false })
      loading.value = false
    }
  }
</script>
